import React, {useEffect, useState} from 'react';
import {Filter, MessageSquare, Search, Trash2} from 'lucide-react';
import {Req} from '../../util/fetch';

interface Comment {
  id: number;
  content: string;
  user: {
    realname: string;
    avatarUrl: string;
    roleName: string;
    position: string;
    type: string;
  };
  train: {
    title: string;
    id: number;
  };
  crtTime: string;
}

export default function AdminComments() {
  const [comments, setComments] = useState<Comment[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<string>('all');

  const events = Array.from(new Set(comments.map(comment => comment?.train?.title)));

  const filteredComments = comments.filter(comment => {
    const matchesSearch = 
      comment.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
        comment.user.realname.toLowerCase().includes(searchTerm.toLowerCase()) ||
        comment.train?.title.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesEvent = selectedEvent === 'all' || comment.train?.title === selectedEvent;

    return matchesSearch && matchesEvent;
  });

  const handleDelete = async (id: number) => {
    if (window.confirm('确定要删除这条评论吗？')) {
      await Req(`/bsTrainComment/batch?ids=${id}`, {method: 'DELETE'});
      alert('删除成功')
      await queryList()
    }
  };

  const queryList = async () => {
    const res = await Req(`/bsTrainComment/list`)
    if (res.success) {
      setComments(res.data)
    } else {
      alert(res.message)
    }
  };

  useEffect(() => {
    queryList()
  }, [])

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">评论管理</h1>
        <p className="text-gray-500">管理所有训练活动的评论</p>
      </div>

      {/* 工具栏 */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <div className="relative w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            <input
              type="text"
              placeholder="搜索评论..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`p-2 rounded-lg ${
              showFilters ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'
            }`}
          >
            <Filter className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* 筛选面板 */}
      {showFilters && (
        <div className="bg-white p-4 rounded-lg shadow-sm mb-6">
          <div className="w-64">
            <label className="block text-sm font-medium text-gray-700 mb-2">活动</label>
            <select
              value={selectedEvent}
              onChange={(e) => setSelectedEvent(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部活动</option>
              {events.map(event => (
                <option key={event} value={event}>{event}</option>
              ))}
            </select>
          </div>
        </div>
      )}

      {/* 评论列表 */}
      <div className="space-y-4">
        {filteredComments.map(comment => (
          <div
            key={comment.id}
            className="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all duration-300"
          >
            <div className="flex items-start justify-between">
              <div className="flex items-start space-x-4">
                <img
                    src={comment.user.avatarUrl}
                    // alt={comment.user.realname}
                  className="w-12 h-12 rounded-full object-cover"
                />
                <div>
                  <div className="flex items-center space-x-2">
                    <span className="font-medium text-gray-900">{comment.user.realname}</span>
                    {/*<span className="text-sm text-gray-500">({comment.user.roleName})</span>*/}
                    <span
                        className="text-sm text-gray-500">({comment.user.type == '0' ? '管理员' : comment.user.position})</span>
                  </div>
                  <div className="text-sm text-gray-500 mb-2">{comment.crtTime}</div>
                  <p className="text-gray-700">{comment.content}</p>
                </div>
              </div>
              <button
                onClick={() => handleDelete(comment.id)}
                className="p-2 text-gray-400 hover:text-red-500 transition-colors"
              >
                <Trash2 className="w-5 h-5" />
              </button>
            </div>
            <div className="mt-4 flex items-center text-sm text-gray-500">
              <MessageSquare className="w-4 h-4 mr-1" />
              来自：{comment.train?.title}
            </div>
          </div>
        ))}

        {filteredComments.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            暂无评论数据
          </div>
        )}
      </div>
    </div>
  );
}